<?php

namespace App\Libs;

class ResponseMessage {
    /**
     * 定义通用报错列表
     *
     * @return	array
     */
    private $failedCodeList;

    private $status;
    private $failedCode;
    private $failedMsg;
    private $data;
    static private $instance;

    public function __construct(){
        self::intFailedCodeList();
        $this->status = 'SUCCESS';
    }

    private function intFailedCodeList(){
        $this->failedCodeList = [
            'ERROR'         => '未知错误',
        ];
    }

    static public function getInstance(){
        if(!(self::$instance instanceof ResponseMessage)){
            self::$instance = new self;
        }
        return self::$instance;
    }

    public function success($data = []){
        $this->status = 'SUCCESS';
        $this->data = $data;
        return $this;
    }

    public function failed($failedCode = null){
        $this->status = 'FAILED';
        $this->failedCode = isset($this->failedCodeList[$failedCode])?$failedCode:'ERROR';
        $this->failedMsg = isset($this->failedCodeList[$failedCode])?$this->failedCodeList[$failedCode]:'未知错误';
        return $this;
    }

    public function setStatus($status){
        $this->status = $status;
        return $this;
    }

    public function setFailedCode($failedCode, $failedMsg){
        $this->failedCode = $failedCode;
        $this->failedMsg = $failedMsg;
        return $this;
    }

    public function setData($data){
        $this->data = $data;
        return $this;
    }

    public function response(){
        if($this->status == 'SUCCESS'){
            $response = ['status' => $this->status, 'data' => $this->data];
        }else{
            $response = ['status' => $this->status, 'failedCode' => $this->failedCode, 'failedMsg' => $this->failedMsg];
        }
        BLogger::getInOutLogger(BLogger::LOG_RESPONSE)->info(json_encode($response));
        return $response;
    }
}
